package com.dashu.authority.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashu.authority.common.Constant;
import com.dashu.authority.entity.AuthenticationInfo;
import com.dashu.authority.exception.AuthorityException;
import com.dashu.authority.repository.SpringContextHolder;
import com.dashu.authority.servie.AuthenticationInfoService;

import net.sf.json.JSONObject;

public class AccessFilter implements Filter {
	private AuthenticationInfoService infoService;
	/**
	 * @author chaoyin
	 */
	private static final String[] IGNORE_URI = { "/login.html", "/Login", "/login", "/Login/" };

	public void destroy() {
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		boolean flag = false;
		String url = request.getRequestURL().toString();
		for (String s : IGNORE_URI) {
			if (url.contains(s)) {
				flag = true;
				break;
			}
		}
		if (flag) {
			filterChain.doFilter(arg0, arg1);
		} else {
			String token = request.getParameter(Constant.AUTH_TOKEN_PARAM_NAME);
			if (token != null && !"".equals(token)) {
				if (token.contains("-")) {
					out(response, -1208, 2, "账号未绑定");
				}
				try {
					AuthenticationInfo info = this.infoService.queryInfoByToken(token);// 查看token
					if (info != null) {
						long expiry = Long.valueOf(info.getExpiry());
						if (expiry > System.currentTimeMillis()) {
							this.infoService.updateInfoByToken(info.getId());// 更新到期时间
							filterChain.doFilter(arg0, arg1);
						} else {
							out(response, -1208, 1, "账号登录超时");
						}
					} else {
						out(response, -1208, 0, "账号尚未登录");
					}
				} catch (AuthorityException e) {
					e.printStackTrace();
					out(response, -1208, 0, "系统异常!");
				}
			} else {
				out(response, -1208, 0, "账号尚未登录");
			}
		}
	}

	private void out(HttpServletResponse response, int status, int errorCode, String errorMsg) throws IOException {
		response.setStatus(200);
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		// 将实体对象转换为JSON Object转换
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("errorCode", errorCode);
		jsonObject.put("status", status);
		jsonObject.put("errorMsg", errorMsg);
		response.setContentType("application/json; charset=utf-8");
		out.append(jsonObject.toString());
		out.flush();
		out.close();
	}

	public void init(FilterConfig arg0) throws ServletException {
		this.infoService = SpringContextHolder.getApplicationContext().getBean(AuthenticationInfoService.class);
	}
}